<?php
/**
 * Services are globally registered in this file
 *
 * @var \Phalcon\Config $config
 */

$di->setShared('config', function(){
    return include APP_PATH . "/config/config.php";
});

/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->setShared('db', function (){
//    try{
        $dbConfig = $this->getConfig()->get('database')->toArray();
        $adapter = $dbConfig['adapter'];
        unset($dbConfig['adapter']);

        $class = 'Phalcon\Db\Adapter\Pdo\\' . $adapter;
        $connection = new $class($dbConfig);

        if(APP_DEV){
            $profiler = new \Phalcon\Db\Profiler();
            $eventsManager = new \Phalcon\Events\Manager();
            $logger = new \Phalcon\Logger\Adapter\File(BASE_PATH . "/cache/logs/sql.log");
            $eventsManager->attach('db', function(\Phalcon\Events\Event $event, Phalcon\Db\Adapter\Pdo $connection) use ($logger, $profiler) {
                if ($event->getType() == 'beforeQuery') {
                    $profiler->startProfile(
                        $connection->getSQLStatement()
                    );
                }
                if ($event->getType() === "afterQuery") {
                    $profiler->stopProfile();
                    $profile = $profiler->getLastProfile();
                    $logger->log(
                        $profile->getSqlStatement(). PHP_EOL .
                        'Time:' . $profile->getTotalElapsedSeconds(), \Phalcon\Logger::INFO);

                }
            });
            $connection->setEventsManager($eventsManager);
        }
        return $connection;
//    }
//    catch(\Exception $e){
//        die('数据库连接失败！' . $e->getMessage());
//    }
});

/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->setShared('modelsMetadata', function () {
    return new \Phalcon\Mvc\Model\Metadata\Memory();
});

/**
 * 设置加密及key
 */
$di->setShared('crypt', function(){
    $crypt = new \Phalcon\Crypt();
    $crypt->setKey($this->getConfig()->get('key'));
    return $crypt;
});
